package com.lfs.dingtalk.robot.web;

import com.dingtalk.open.app.api.OpenDingTalkClient;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import com.lfs.dingtalk.robot.constants.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import shade.com.alibaba.fastjson2.JSON;
import shade.com.alibaba.fastjson2.JSONObject;

import javax.annotation.PostConstruct;

import static com.lfs.dingtalk.robot.servcie.PersistenceConnectionHolder.yourListener;


@RequestMapping("/dingTalk")
@RestController
@Slf4j
public class CallbackController {


    @PostConstruct
    public void subscribe() throws Exception {
        OpenDingTalkStreamClientBuilder
                .custom()
                .credential(new AuthClientCredential(CommonConstant.APP_KEY, CommonConstant.APP_SECRET))
                //注册事件监听
                .registerAllEventListener(event -> {
                    try {
                        //事件唯一Id
                        String eventId = event.getEventId();
                        //事件类型
                        String eventType = event.getEventType();
                        //事件产生时间
                        Long bornTime = event.getEventBornTime();
                        //获取事件体
                        JSONObject bizData = event.getData();
                        log.info(eventId+"  "+eventType+"  "+bornTime);
                        log.warn(String.valueOf(bizData));
                        //处理事件
//                            process(bizData);
                        //消费成功
                        return EventAckStatus.SUCCESS;
                    } catch (Exception e) {
                        //消费失败
                        return EventAckStatus.LATER;
                    }
                })
                .registerCallbackListener("/v1.0/card/instances/callback", yourListener)
                .build().start();
    }


    /**
     * 服务号接收消息
     * @return
     */
    @Bean
    public CommandLineRunner init(){
        return args -> {
            OpenDingTalkClient client = OpenDingTalkStreamClientBuilder
                    .custom()
                    .credential(new AuthClientCredential(CommonConstant.APP_KEY, CommonConstant.APP_SECRET))
                    .registerCallbackListener("/v1.0/im/bot/messages/get", new RobotMsgCallbackConsumer())
                    .build();
            client.start();
        };
    }

    public static class RobotMsgCallbackConsumer implements OpenDingTalkCallbackListener<JSONObject, JSONObject> {
        @Override
        public JSONObject execute(JSONObject request) {
            System.out.println(JSON.toJSONString(request));
            try {
                JSONObject text = request.getJSONObject("text");
                if (text != null) {
                    //机器人接收消息内容
                    String msg = text.getString("content").trim();
                    String openConversationId = request.getString("conversationId");
                }
            } catch (Exception e) {
                log.error("receive group message by robot error:" +e.getMessage(), e);
            }
            return new JSONObject();
        }
    }

}
